<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="../css/jsdeliverbootstrap.min.css">
<!--    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"-->
<!--          integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">-->
    <link rel="stylesheet" href="../css/pet-store-plus.css">
    <link rel="stylesheet" href="/css/staticfilebootstrap.min.css">
<!--    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">-->

    <script src="/js/chart.js"></script>
<!--    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->
    <title>订单管理</title>

</head>
<body>

<div th:replace="seller_commom"></div>


<!--  url    /admin/order_status     需要自己重新将list填进去-->
<div class="content" id="content">
    <div id="myModal1" class="modal1" style="display: none">

        <div class="modal-content-order">
            <div id="modalTab-bg">
                <table id="order-details">
                    <thead>
                    <tr>
                        <th>商品Id</th>
                        <th>数量</th>
                        <th>单价</th>
                    </tr>
                    </thead>
                    <tbody id="order-details-tbody"></tbody>
                </table>
            </div>
            <div id="button-return">
                <button onclick="closeModal1()" class="Button" style="grid-row: span 1;width: 30%">返回</button>
            </div>
        </div>
    </div>
    <div class="order-check">
        <div>
            <input type="checkbox" name="order_status" id="pay" style="vertical-align:middle; display: inline-block;">
            <label for="pay" style="display: inline-block">已支付</label>
        </div>
        <div>
            <input type="checkbox" name="order_status" id="send" class="order-checkInput">
            <label for="send" class="order-checkLabel">已发货</label>
        </div>
        <div>
            <input type="checkbox" name="order_status" id="receive">
            <label for="receive">已收货</label>
        </div>
        <div>
            <input type="checkbox" name="order_status" id="return">
            <label for="return">已退货</label>
        </div>
        <div>
            <input type="checkbox" name="order_status" id="cancel">
            <label for="cancel">已取消</label>
        </div>
    </div>
    <div class="searchgrp" >
        <form >
            <input type="text" placeholder="可通过商品名搜索..." class="searchinput" id="orderSearch">
            <button class="searchbtn" type="button" onclick="searchOrder()">搜索</button>
<!--            ///admin/getOrderListByKeyForJS url-->
        </form>
    </div>
    <div class="tab-bg">
    <table class="order_tab" th:fragment="ordertab" id="ordertab">
          <caption></caption>
          <thead>
          <tr>
              <th>订单id</th>
              <th>买家ID</th>
              <th>商户订单号</th>
              <th>实际金额</th>

<!--              <th>订单状态</th>-->
              <th>支付</th>
              <th>发货</th>
              <th>收货</th>
              <th>退货</th>
              <th>取消</th>

              <th>订单操作</th>
          </tr>
          </thead>
        <tbody id="orderTabBody">
           <tr th:each="data:${orderList}" >
               <td th:text=" ${data.orderid}"></td>
               <td th:text="${data.username}"></td>
               <td th:text="${data.outtradeno}"></td>
               <td th:text="${data.totalprice}"></td>
               <td th:with="result=${data.ispay == true} ? '是' : '否'">
                   <p class="ispay">
                       [[${result}]]
                   </p>
               </td>
               <td th:with="result=${data.issend == true} ? '是' : '否'">
                   <p class="issend">
                       [[${result}]]
                   </p>
               </td>
               <td th:with="result=${data.isget == true} ? '是' : '否'">
                   <p class="isget">
                       [[${result}]]
                   </p>
               </td>
               <td th:with="result=${data.isreturn == true} ? '是' : '否'">
                   <p class="isreturn">
                       [[${result}]]
                   </p>
               </td>
               <td th:with="result=${data.iscancel == true} ? '是' : '否'">
                   <p class="iscancel">
                       [[${result}]]
                   </p>
               </td>

               <td style="text-align: center; vertical-align: middle;">
<!--                   <button class="Button" style="display: inline-block;" th:onclick="orderDetail([[${data.orderid}]],this)">查看详情</button>-->
<!--                   <button class="Button" style="display: inline-block;"  th:onclick="deleteOrder([[${data.orderid}]],this);">删除订单</button>-->
                   <button class="Button" th:onclick="orderDetail([[${data.orderid}]],this)"style="display: inline-block;">查看详情</button>
                   <button class="Button"   th:onclick="deleteOrder([[${data.orderid}]],this);" style="display: inline-block;">删除订单</button>
                   <button class="longButton Button" th:style="${data.ispay == true and data.issend == false ? '' : 'display:none'}"
                           onclick="sendOrder(this)">去发货</button>
<!--                   /admin/getOrder-->
<!--                   删除按钮   /admin/deleteOrder   页面删掉该行-->
               </td>
           </tr>
        </tbody>
    </table>
    </div>
</div>

<script th:inline="javascript">
    const tbody = document.getElementById('orderTabBody');

    window.onload = function() {
        const checkboxes = document.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach((checkbox) => {
            checkbox.addEventListener('change', function() {
                let statusString = '';
                checkboxes.forEach((cb) => {
                    statusString += cb.checked ? '1' : '0';
                });

                var xhr = new XMLHttpRequest();
                xhr.open("POST", "/admin/order_status", true);
                xhr.setRequestHeader("Content-Type", "application/json");
                xhr.send(JSON.stringify({ status: statusString }));
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        var response = JSON.parse(xhr.responseText);
                        var orderdata = response.data;

                        // 清空原有数据
                        tbody.innerHTML = '';
                        updateOrder(orderdata)
                    }
                };
            });
        });
    };
    function searchOrder(){
        console.log('search');
        var keywords=document.getElementById('orderSearch').value;
        console.log(keywords);
        var url='/admin/getOrderListByKeyForJS?keyword='+keywords;
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok.');
                }
                return response.json(); // 解析JSON格式的响应数据
            })
            .then(data => {
                // 处理返回的数据
                console.log(data);
                tbody.innerHTML = '';
                var newitems = data.data;

                updateOrder(newitems);
            })
            .catch(error => {
            console.error('请求发生错误', error);
        });
    }
    function updateOrder(orderdata){
        // 更新表格数据
        orderdata.forEach(function(item) {
            var newRow = document.createElement('tr');
            let statusText = '';
            // if (item.iscancel === true) {
            //     statusText = '已取消';
            // } else if (item.ispay === false) {
            //     statusText = '未支付';
            // } else if (item.ispay === true && item.issend === false) {
            //     statusText = '未发货';
            // } else if (item.ispay === true && item.issend === true && item.isget === false) {
            //     statusText = '未收货';
            // } else if (item.ispay === true && item.issend === true && item.isget === true && item.isreturn === false) {
            //     statusText = '已完成';
            // } else if (item.ispay === true && item.issend === true && item.isget === true && item.isreturn === true) {
            //     statusText = '已退货';
            // // }
            // newRow.innerHTML = `
            //                 <td>${item.orderid}</td>
            //                 <td>${item.username}</td>
            //                 <td>${item.totalprice}</td>
            //                  <td> <span>${statusText}</span></td>
            //                 <td style="text-align: center; vertical-align: middle;">
            //                     <button class="Button" style="display: inline-block;">查看详情</button>
            //                     <button class="Button" style="display: inline-block;" onclick="deleteOrder(${item.orderid}, this);">删除订单</button>
            //                 </td>
            //             `;

            var text1='否';
            var text2='否';
            var text3='否';
            var text4='否';
            var text5='否';
            var sendText;

            if (item.ispay === true) {
                text1 = '是';
            }
            if (item.issend === true) {
                text2 = '是';
            }
            if (item.isget===true) {
                text3 = '是';
            }
            if (item.isreturn===true) {
                text4 = '是';
            }
            if (item.iscancel) {
                text5 = '是';
            }
            if(item.ispay==true&&item.issend==false){
                sendText=true;
            }else {
                sendText=false;
            }

            newRow.innerHTML = `
                            <td>${item.orderid}</td>
                            <td>${item.username}</td>
                            <td>${item.outtradeno}</td>
                            <td>${item.totalprice}</td>
                            <td> <span>${text1}</span></td>
                            <td> <span>${text2}</span></td>
                            <td> <span>${text3}</span></td>
                            <td> <span>${text4}</span></td>
                            <td> <span>${text5}</span></td>

                            <td style="text-align: center; vertical-align: middle;">
                                <button class="Button" style="display: inline-block;">查看详情</button>
                                <button class="Button" style="display: inline-block;" onclick="deleteOrder(${item.orderid}, this);">删除订单</button>
                                ${sendText ? '<button class="longButton Button" onclick="sendOrder(this)">去发货</button>' : ''}
                            </td>
                        `;


            console.log(newRow.innerHTML);
            tbody.appendChild(newRow);
        });
    }

    function  deleteOrder(orderId,button){
        console.log("deleteOrder");
        var row = button.parentNode.parentNode;
        var url = "/admin/deleteOrder?orderId=" + orderId;
        var result = confirm("Are you sure you want to delete the order "+orderId+"?");

        if (result) {
            fetch(url, {
                method: 'GET',
            })
                .then(response => {
                    if (response.ok) {
                        console.log()
                       return response.json();
                    } else {
                        console.log("请求失败，状态码：" + response.status);
                    }
                }).then(data=>{
                    console.log()
                    if(data.status===1){
                        console.log("删除成功");
                        alert('订单'+orderId+'删除成功');
                        row.remove();
                    }else{
                        console.log("删除失败");
                    }

            })
                .catch(error => {
                    console.error('发生错误:', error);
                });
        } else {
            // 如果用户点击取消，可以选择执行其他操作或不执行任何操作
            console.log("Action cancelled by user");
        }






    }
    function orderDetail(orderId,button){
        var row=button.parentNode.parentNode;
        var os=document.getElementById('.os');

        var modal=document.getElementById('myModal1');
        modal.style.display="block";
        console.log('orderid='+orderId);
        var url='/admin/getOrder?orderId='+orderId;
        fetch(url,{
            method:'GET',
        })
            .then(response=>response.json())
            .then(data=>{
                console.log(data);
                if(data.status===1){
                    updataDetailsOrder(data.data);
                }
            })
            .catch(error=>{
                console.log('请求发送失败:', error);
            });
    }
    function closeModal1(){
        console.log('关闭弹窗');
        var modal=document.getElementById('myModal1');
        modal.style.display="none";
    }
    function updataDetailsOrder(newData){
        console.log('updataDetailsOrder');
            const modalTab=document.getElementById('order-details');
            const tbody=document.getElementById('order-details-tbody');
            tbody.innerHTML='';
            newData.forEach(function (item){
                var newRow = document.createElement('tr');
                newRow.innerHTML=`
                <td>${item.itemid}</td>
                <td>${item.quantity}</td>
                <td>${item.unitprice}</td>

                `;
                tbody.appendChild(newRow);
            })
    }

    function sendOrder(button){
        var row=button.parentNode.parentNode;
        var orderid=row.querySelector('td:nth-child(1)').innerText;
        var url="/admin/sendOrder?orderId="+orderid;
        fetch(url,{
            method:'GET',
        }) .then(response => {
            if (response.ok) {
                var status=row.querySelector('td:nth-child(6)');
                status.innerText = "是";
                button.style.display = "none";  // 直接设置样式属性而不是修改 style 属性的整个值
                alert('订单'+orderid+'发货成功');
            } else {
                console.log("请求失败，状态码：" + response.status);
            }
        })
            .then(data=>{
            })
            .catch(error => {
                console.error('发生错误:', error);
            });
    }

</script>
</body>
</html>